using System.Web.Mvc;
using System.Web.Mvc.ActiveRecordSupport;
using Castle.ActiveRecord;
using MVCActiveRecordIntegration.Models;

namespace MVCActiveRecordIntegration.Controllers {
    public class PersonController : Controller {
        //
        // GET: /Person/

        public ActionResult Index() {
            return View(ActiveRecordMediator<Person>.FindAll());
        }

        //
        // GET: /Person/Details/5

        public ActionResult Details([ARFetch("id")] Person person) {
            if (person == null)
                return RedirectToAction("Index");
            return View(person);
        }

        //
        // GET: /Person/Create

        public ActionResult Create() {
            return View();
        }

        //
        // POST: /Person/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection) {
            try {
                var p = new Person();
                UpdateModel(p, collection.ToValueProvider());
                ActiveRecordMediator<Person>.Save(p);
                return RedirectToAction("Index");
            } catch {
                return View();
            }
        }

        //
        // GET: /Person/Edit/5

        public ActionResult Edit([ARFetch("id")] Person person) {
            return View(person);
        }

        //
        // POST: /Person/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit([ARFetch("id")] Person person, FormCollection collection) {
            try {
                UpdateModel(person, collection.ToValueProvider());
                ActiveRecordMediator<Person>.Update(person);
                return RedirectToAction("Index");
            } catch {
                return View();
            }
        }
    }
}